<template>
  <div>
    <div class="home-box box-3-list">
      <div class="center-box1">
        <div class="box-title-1">
          <img src="@/assets/image/5.webp" alt="">
          <div class="center">
            <p>恋爱聊天室</p>
            <p>恋爱聊天室，不要说脏话哦～</p>
          </div>
        </div>
        <div class="box-bottom-1">
          <div class="box-left">
            <a href="javascript:void (0)"
               v-for="(item,index) in tableData"
               :key="index"
               @click="changeUser(item)"
               :class="{active:item.followId === active}"
               class="item">
              <img class="avatar" :src="item.followCover" alt="">
              <div class="right-box">
                <p class="title">{{ item.followUsername }}</p>
                <p class="tips over-hide-1">
                  快来和他聊天吧～
<!--                  <i style="color: #fc476d" class="el-icon-female" v-if="item.gender===1"></i>-->
<!--                  <i style="color: #5c85e4" class="el-icon-male" v-else></i>-->
                </p>
              </div>
<!--              <a href="javascript:void (0)" @click.stop="unLike(item)"><i class="el-icon-close"></i></a>-->
            </a>
          </div>
          <div class="box-right">
            <div class="top-chat" v-loading="isLoading">
              <el-empty v-if="messageData.length<1"></el-empty>
                <div class="item" v-if="messageData.length>0" v-for="(item,index) in messageData" :key="index">
                  <img :src="item.userCover" class="avatar" alt="">
                  <div class="right" :class="{mine:item.userId===userInfo.id}">
                    {{item.message }}
                  </div>
                </div>

            </div>
            <div class="bot-input">
              <el-input :rows="2" v-model="message" type="textarea" placeholder="请输入..."></el-input>
              <a class="btn-box" @click="sendMessage" href="javascript:void (0)">发送</a>
            </div>
          </div>
        </div>
      </div>
    </div>

    <lz-update-user :is-show="isShow"></lz-update-user>

    <lz-footer></lz-footer>



  </div>
</template>

<script>
import WebSocketClient from "@/utils/scoket";
import {getFollowList, selectMessageHistory, sendMessages, unLikeUser} from "@/api/apiFox";
export default {
  data() {
    return {
      isShow:false,
      active:1,
      message:"",
      tableData:[],
      isLoading:false,
      messageData:[],
      chatUser:{},
      userInfo:{},
      queryParams:{
        pageNum:1,
        pageSize:100
      },
      wsClient: null,
      receivedMessage:""
    }
  },
  methods:{
    // 初始化 WebSocket 连接
    initWebSocket() {
      const socketUrl = process.env.VUE_APP_WEBSOCKET; // 使用环境变量获取 WebSocket 地址
      this.wsClient = new WebSocketClient(socketUrl);
      this.wsClient.setOnReceiveMessage(this.handleReceivedMessage);
      this.wsClient.init();
    },

    // 处理接收到的消息
    handleReceivedMessage(message) {
      console.log("接收到消息:", message);
      if (message === 'message'){
        this.messageHistory(this.chatUser.followId)
      }
      this.receivedMessage = message; // 更新接收到的消息
    },

    unLike(item){
      unLikeUser({userId:item.id}).then(res=>{
        this.$message.success('已取消关注')
        if (item.id === this.active){
          this.messageData = []
        }
        this.getList(this.queryParams)
      }).catch(err=>{})
    },

    sendMessage(){
      console.log(this.chatUser)
      if (this.message===""){
        this.$message.error('发送内容不能为空哦～')
      }else{

        sendMessages({
          chatUserId:this.chatUser.followId,
          chatUserCover:this.chatUser.followCover,
          chatUsername:this.chatUser.followUsername,
          message:this.message
        }).then(res=>{
          this.message = ""
          this.messageHistory(this.chatUser.followId)
        }).catch(err=>{})
      }

    },

    getList(queryParams){
      getFollowList(queryParams).then(res=>{
        console.log(this.$route.query.id)
          this.tableData= res.list
          if (this.$route.query.id){
            if (this.tableData && this.tableData.length>0){

              res.list.forEach(value=>{
                console.log(value)
                if (value.followId === Number(this.$route.query.id)){
                  this.messageHistory(value.followId)
                  this.active = value.followId
                  this.chatUser=value
                }
              })
            }else{
              this.active = null
            }
          }
      }).catch(err=>{})
    },

    changeUser(item){
      this.active = item.followId
      this.isLoading = true
      this.chatUser = item
      this.messageHistory(item.followId)
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const chatContainer = this.$el.querySelector('.top-chat');
        chatContainer.scrollTop = chatContainer.scrollHeight;
      });
    },


    // 查询聊天历史
    messageHistory(item){
      selectMessageHistory({chatUserId:item}).then(res=>{
         this.messageData= res.reverse()
        this.isLoading = false
      }).catch(err=>{
        this.messageData= []
        this.isLoading = false
      })
    }
  },
  watch: {
    // 每当消息列表变化时，调用滚动到底部
    messageData() {
      this.scrollToBottom();
    }
  },
  updated() {
    this.scrollToBottom();
  },
  mounted() {
    this.scrollToBottom();
    this.initWebSocket();
    this.getList(this.queryParams)
    this.$store.dispatch('getUserList').then(res=>{
      console.log(res,'wewqeewq')
      this.userInfo = res
      if (this.wsClient) {
        this.wsClient.sendMessage(JSON.stringify({id:res.id})); // 通过 WebSocket 发送消息
      }else{
        this.$message.error('断线重连了～')
      }
    })
  },
  beforeDestroy() {
    if (this.wsClient) {
      this.wsClient.close();
    }
  },
}
</script>

<style scoped lang="scss">
.home-box {
  width: 100%;
  min-height: calc(100vh - 140px);
  background: var(--homeBgk);
  display: flex;
  justify-content: center;

  .home-center {
    width: 800px;
    min-height: calc(100vh - 140px);
    display: flex;
    justify-content: space-between;
    //background: #fff;

  }
}

.box-nav-list {
  background: var(--navBgk);
  height: 200px !important;
  margin-bottom: -200px;

  .home0-center {
    width: 800px;
    padding-top: 120px;
    display: flex;
    height: 200px;
    justify-content: space-between;

    .item {
      width: 300px;
      height: 300px;
      text-align: center;

      .nav-box {
        width: 100%;
        height: 120px;
        border-radius: 50%;

        img {
          width: 100px;
          height: 100px;
          object-fit: cover;
        }
      }

      .title {
        font-size: 22px;
        color: var(--textColor);
        font-weight: 600;
      }

      .box-center {
        margin-top: 15px;
        font-size: 12px;
        color: var(--colorTip);
      }
    }
  }
}

.box-3-list {
  width: 100%;
  background: var(--navBgk);
  padding-bottom: 150px;
  padding-top: 45px;

  .center-box1 {
    width: 900px;

    .box-title-1 {
      width: 100%;
      text-align: center;
      position: relative;

      .center {
        width: 100%;
        position: absolute;
        margin-top: -30px;

        p:nth-child(1) {
          font-size: 28px;
          font-weight: 600;
          color: #fc476d;
        }

        p:nth-child(2) {
          font-size: 12px;
          color: var(--colorTip);
        }
      }
    }

    .box-bottom-1{
      width: 100%;
      margin-top: 100px;
      min-height: 200px;
      display: flex;
      justify-content: space-between;
      .box-left{
        width: 200px;
        min-height: 200px;
        background: var(--menuList);

        .item{
          width: 100%;
          min-height: 45px;
          padding: 10px;
          box-sizing: border-box;
          border-bottom: 1px solid var(--footerTop);
          display: flex;
          align-items: center;
          .avatar{
            height: 40px;
            width: 40px;
            object-fit: cover;
            border-radius: 50%;
          }
          .right-box{
            width: calc(100% - 40px);
            margin-left: 10px;
            .title{
              font-size: 14px;
              color: var(--navCircle);
            }
            .tips{
              font-size: 12px;
              color: var(--footerTip);
              i{
                font-weight: 600;
              }
            }
          }
        }
        .active{
          background: var(--chatBgk);
          .right-box{
            .title{
              color: var(--chatActive);
            }
            .tips{
              color: var(--chatTips);
              i{
                font-weight: 600;
              }
            }
          }
        }
      }
      .box-right{
        min-height: 100px;
        //background: red;
        width: calc(100% - 200px);
        padding: 10px;
        box-sizing: border-box;

        .top-chat{
          width: 100%;
          border-bottom: 1px solid var(--footerTop);
          height: 400px;
          overflow-y: scroll;
          padding-right: 50px;
          box-sizing: border-box;
          .item{
            width: 100%;
            margin-bottom: 10px;
            display: flex;
            .avatar{
              width: 36px;
              height: 36px;
              object-fit: cover;
              border-radius: 50%;
              outline: 1px solid var(--footerTop);
            }
            .right{
              min-width: 50px;
              min-height: 40px;
              border-radius: 10px;
              margin-left: 10px;
              background: var(--messageBgk);
              display: flex;
              align-items: center;
              //padding-left: 10px;
              box-sizing: border-box;
              font-size: 13px;
              color: var(--textColor);
              padding: 10px;
              line-height: 22px;
            }
            .mine{
              background: #96ed6a;
            }
          }
        }
        .bot-input{
          width: 100%;
          display: flex;
          padding-top: 10px;
          .btn-box{
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            background: #fc476d;
            font-size: 16px;
            width: 130px;
            height: 55px;
            margin-left: 20px;
            border-radius: 6px;
          }
        }
      }
    }

    .box-2-nav {
      width: 100%;
      margin-top: 100px;
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;

      .box-item {
        margin-bottom: 25px;
        width: 278px;
        min-height: 480px;
        background: var(--itemBgk);
        //border-radius: 10px;
        overflow: hidden;
        padding: 10px;
        box-sizing: border-box;
        box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;

        .image {
          width: 100%;
          height: 250px;
          object-fit: cover;
        }

        .nav {
          width: 100%;
          margin-top: 15px;
          display: flex;
          justify-content: space-between;

          .left-icon {
            font-size: 14px;
            color: var(--navCircle);

            i {
              color: #fc476d;
            }
          }
        }

        .nav-content {
          font-size: 14px;
          margin-top: 10px;
          color: var(--colorTip);
        }

        .btn {
          width: 100%;
          height: 40px;
          display: flex;
          justify-content: center;
          margin-top: 18px;
          align-items: center;
          border: 1px solid var(--switchBorder);
          color: var(--activeColor);
        }
      }

      .box-item-length {
        width: 48%;
        margin: 10px 0;
        min-height: 150px;
        padding: 10px;
        background: var(--itemBgk);
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;

        .img-left {
          width: 220px;
          height: 220px;
          object-fit: cover;
        }

        .right-box {
          width: calc(100% - 220px);
          margin-left: 15px;
          padding-top: 15px;
          box-sizing: border-box;

          .titles {
            font-weight: 600;
            font-size: 18px;
            color: var(--navCircle);
          }

          .time {
            font-size: 16px;
            color: var(--navCircle);
            margin-top: 10px;
          }

          .btn-bot {
            margin-top: 20px;
            width: 200px;
            height: 42px;
            border-radius: 5px;
            background: var(--activeColor);
            color: var(--navBgk);
            font-size: 14px;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }
    }
    .table{
      margin-top: 120px;
    }
    .box-bottom {
      width: 100%;
      display: flex;
      //justify-content: center;
      margin-top: 30px;
    }
  }
}

</style>
